//
//  SHPStatusDAL.swift
//  weibo
//
//  Created by songhuipan on 16/4/28.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit

class SHPStatusDAL: NSObject {
    
    class func getHomeStatus (since_id: Int64, max_id: Int64,callback:(array:[[String:AnyObject]])->()) {
        
        let status = checkoutCacheStatus(since_id, max_id: max_id)
        if status.count == 0 {
            NetworkTools.sharedTools.loadStatus((SHPUserAccountViewModel.sharedUserAccount.account?.access_token)!, since_id: since_id, max_id: max_id, finish: { (responseObject, error) -> () in
                if error != nil{
                    print(error)
                    callback(array: [])
                    return
                }
            
                guard let array = responseObject?["statuses"] as? [[String:AnyObject]] else{
                    print("返回的不是一个数组")
                    callback(array: [])
                    return
                }
//                print(array)
                print("网络数据")
                callback(array: array)
                saveStatus(array)
            })
        }else {
            print("缓存数据")
            callback(array: status)
        }
    }
    
    class func checkoutCacheStatus(since_id: Int64, max_id: Int64)->[[String:AnyObject]] {
//        if since_id == 0 && max_id == 0 {
//            return[]
//        }
        // 获取用户的id
        let userId = SHPUserAccountViewModel.sharedUserAccount.account!.uid!
        var sql = "SELECT status FROM T_Status WHERE userId = \(userId) "
        // 下拉刷新
        if since_id > 0 {
            
            sql += " AND statusId >\(since_id)"
        }
        // 上拉加载更多
        if max_id > 0 {
            sql += " AND statusId <\(max_id)"
        }
        // 限制查询条数
        sql += " ORDER BY statusId DESC LIMIT 20"
        var tempArray :[[String:AnyObject]] = [[String:AnyObject]]()
        
        SQLManager.sharedTools.queue.inDatabase { (db) -> Void in
            do{
                let result = try db.executeQuery(sql)
                
                while result.next(){
                    let status = result.dataForColumn("status")
                    let dic = try! NSJSONSerialization.JSONObjectWithData(status, options: []) as! [String:AnyObject]
                    tempArray.append(dic)
                }
            }catch{
                print(error)
            }
        }
        return tempArray
    }
    class func saveStatus(array:[[String:AnyObject]]) {
        let userId = SHPUserAccountViewModel.sharedUserAccount.account!.uid!
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?)"
        SQLManager.sharedTools.queue.inTransaction { (db, rollback) -> Void in
            for dic in array {
                do {
                    let statusId = dic["id"] as! NSNumber
                    let status = try! NSJSONSerialization.dataWithJSONObject(dic, options: [])
                    try db.executeUpdate(sql, statusId,status,userId)
                    
                }catch{
                    print(error)
                    rollback.memory = true
                    
                }
            }
        }
    }
}






















